package com.fwtai.service.api;

import com.fwtai.tool.ToolClient;
import com.fwtai.tool.ToolSms;
import com.fwtai.tool.ToolString;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class CodeService{

  private final StringRedisTemplate stringRedisTemplate;

  public CodeService(final StringRedisTemplate stringRedisTemplate){
    this.stringRedisTemplate = stringRedisTemplate;
  }

  public String getCode(final String phone){
    if(phone == null || phone.length() == 0){
      return ToolClient.jsonValidateField();
    }
    final boolean verifyPhone = ToolString.verifyPhone(phone);
    if(!verifyPhone){
      return ToolClient.createJsonFail("手机号码有误");
    }
    final String code = ToolString.getRandomCode();
    final boolean b = ToolSms.sendSms(phone,code);
    if(b){
      stringRedisTemplate.opsForValue().set(phone,code,5,TimeUnit.MINUTES);
      return ToolClient.createJsonSuccess("验证码发送成功");
    }else{
      return ToolClient.createJsonFail("发送失败,稍候重试");
    }
  }

  /**
   * 校验验证码
   * @param clear 是否清除,即是否仅能使用1次
   * @作者 田应平
   * @QQ 444141300
   * @创建时间 2024/3/4 12:40
  */
  public String verify(final String phone,final String code,final boolean clear){
    if(phone == null || phone.length() == 0 || code == null || code.length() == 0){
      return ToolClient.jsonValidateField();
    }
    try{
      final boolean verifyPhone = ToolString.verifyPhone(phone);
      if(!verifyPhone){
        return ToolClient.createJsonFail("手机号码有误");
      }
      final Boolean hasKey = stringRedisTemplate.hasKey(phone);
      if(hasKey == null || !hasKey){
        return ToolClient.createJsonFail("验证码已失效,请重新获取");
      }
      final String value = stringRedisTemplate.opsForValue().get(phone);
      if(code.equals(value)){
        if(clear){
          stringRedisTemplate.delete(phone);
        }
        return null;
      }else{
        return ToolClient.createJsonFail("验证码不正确,请重新输入");
      }
    }catch(final Exception e){
      return ToolClient.createJsonFail("验证码已失效,请重新获取");
    }
  }
}